var flagDate = undefined;
var chargingFixedPriceNameList = [];
var chargingTimePriceNameList = [];
var summaryBalanceData = [];
var subBranchCompanyBalanceData = [];
var lineBalanceData = [];
var totalChargingKWHData = [];
var chargingCountData = [];
var totalPriceData = [];
var subBranchCompanyNameData = [];
var balanceBillNameList = [];
var costRatioNameList = [];
var lineNameList = [];
var tabFlag = "summaryBalance";
var exportFlag = undefined;

$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	$ajaxList('searchBalanceInitSetting', getBalanceInitSetting);
	$("#BalanceRatio").hide();
	setTimeout(hideLoading, 500);
})
function getBalanceInitSetting(data){
	var balanceInitSettingData = data.balanceInitSettingList[0]
	$("#ChargingPriceType").val(balanceInitSettingData.balanceBusPriceType);
	$("#BalanceRatioType").val(balanceInitSettingData.balanceRatioType);
	var balanceStartMonth = balanceInitSettingData.balanceStartMonth
	changeYear(0, balanceStartMonth);
	showMonth(getSystemTime().getMonth() + 1);
}
function initChargingPriceName(type) {
	var selectLength = $("#EffectiveDate option").length;
	if (selectLength < 1) {
		getChargingPriceName(type);
	}
}
function getChargingPriceName(type) {
	if (type == '1') {
		if (chargingFixedPriceNameList.length > 1) {
			getChargingFixedPriceName(chargingFixedPriceNameList);
		} else {
			$ajaxList('chargingFixedPriceName', getChargingFixedPriceName);
		}
	} else if (type == '2') {
		if (chargingTimePriceNameList.length > 1) {
			getChargingTimePriceName(chargingTimePriceNameList);
		} else {
			$ajaxList('chargingTimePriceName', getChargingTimePriceName);
		}
	}
}
function getChargingFixedPriceName(data) {
	chargingFixedPriceNameList = data;
	$("#ChargingPrice").empty();
	$("#ChargingUnitPrice").empty();
	$("#EffectiveDate").empty();
//	$("#EffectiveDate").append("<option value='' selected='selected'>请选择</option>");
	var length = data.length;
	if (length == 0) {
		initTable();
		$("#EffectiveDate").attr('disabled', 'disabled');
		showMessge(messageContent["Balance.ChargingPriceNotFound"]);
		return;
	}
	var chargingPrice = undefined;
	for (var i = 0; i < length; i++) {
		chargingPrice = '固：' + data[i].chargingPrice + '元';
		if (data[i].enabled) {
			$("#EffectiveDate").append("<option value='" + chargingPrice + "' selected='selected'>" + date2String(data[i].effectiveDTTM) + "</option>");
			getChargingPrice(chargingPrice);
			$("#ChargingUnitPrice").val(data[0].chargingPrice);
		} else {
			$("#EffectiveDate").append("<option value='" + chargingPrice + "'>" + date2String(data[i].effectiveDTTM) + "</option>");
		}
		$("#EffectiveDate").attr('disabled', false);
	}
	if (!$("#ChargingPrice").text()) {
		getChargingPrice('固：' + data[0].chargingPrice + '元');
		$("#ChargingUnitPrice").val(data[0].chargingPrice);
	}
}
function getChargingTimePriceName(data) {
	chargingTimePriceNameList = data;
	$("#ChargingPrice").empty();
	$("#ChargingUnitPrice").empty();
	$("#EffectiveDate").empty();
//	$("#EffectiveDate").append("<option value='' selected='selected'>请选择</option>");
	var length = data.length;
	var length = data.length;
	if (length == 0) {
		initTable();
		showMessge(messageContent["Balance.ChargingPriceNotFound"]);
		$("#EffectiveDate").attr('disabled', 'disabled');
		return;
	}
	var chargingPrice = undefined;
	for (var i = 0; i < length; i++) {
		chargingPrice = '尖:' + data[i].sharpChargingPrice +'元， 峰:' + data[i].peakChargingPrice + '元， 平:' + data[i].flatChargingPrice + '元， 谷:' + data[i].valleyChargingPrice + '元';
		if (data[i].enabled) {
			$("#EffectiveDate").append("<option value='" + chargingPrice + "' selected='selected'>" + date2String(data[i].effectiveDTTM) + "</option>");
			getChargingPrice(chargingPrice);
		} else {
			$("#EffectiveDate").append("<option value='" + chargingPrice + "'>" + date2String(data[i].effectiveDTTM) + "</option>");
		}
		$("#EffectiveDate").attr('disabled', false);
	}
	if (!$("#ChargingPrice").text()) {
		getChargingPrice('尖:' + data[0].sharpChargingPrice +'元， 峰:' + data[0].peakChargingPrice + '元， 平:' + data[0].flatChargingPrice + '元， 谷:' + data[0].valleyChargingPrice + '元');
	}
}
function getChargingPrice(chargingPrice) {
	$("#ChargingPrice").text(chargingPrice);
	search();
}
function getBalanceBillName(data) {
	balanceBillNameList = data || [];
	$("#BalanceBillID").empty();
	$("#BalanceBillID").append("<option value='' selected='selected'>请选择</option>");
	$("#billErrorMessage").hide();
	$("#billErrorMessage").empty();
	var length = data.length;
	if (length == 0) {
		$("#BalanceRatio").hide();
		$("#billErrorMessage").show();
		$("#billErrorMessage").text(messageContent["Balance.MonthBalanceBillNotExist"]);
//		showMessge(messageContent["Balance.MonthBalanceBillNotExist"]);
		return;
	} else {
		var costRatioCreate = "";
		for (var i = 0; i < length; i++) {
			if (data[i].createFlag) {
				costRatioCreate = '(系数未生成)';
			}
//			else {
//				costRatioCreate = '(系数已生成)';
//			}
			$("#BalanceBillID").append("<option value='" + data[i].balanceBillID + "'>" + (data[i].balanceBillName + costRatioCreate) + "</option>");
		}
		if (!$("#BalanceBillID").val()) {
			$("#BalanceBillID").tips({
				side : 2,
				msg : "请选择电力结算单",
				bg : '#AE81FF',
				time : 1
			});
			$("#BalanceBillID").focus();
			initTable();
			return;
		}
	}
}
function getBalanceBill(index) {
	$("#BalanceRatio").hide();
	$("#CostRatioName").empty();
	if (!$("#BalanceBillID").val()) {
		$("#BalanceBillID").tips({
			side : 2,
			msg : "请选择电力结算单",
			bg : '#AE81FF',
			time : 1
		});
		$("#BalanceBillID").focus();
		initTable();
		return;
	}
	if (balanceBillNameList[index-1] && balanceBillNameList[index-1].createFlag) {
		$("#BalanceRatio").hide();
		$("#CostRatioName").text('');
		showMessge(messageContent["Balance.BalanceRatioNotCreate"]);
		initTable();
		return;
	} else {
		$ajaxList('costRatioName', getChargingCostRatioName, {BalanceMonth: $("#balanceMonth").val(), BalanceBillID: $("#BalanceBillID").val()});
	}
	
}
function getBalanceRatioType(balanceRatioType) {
	if (costRatioNameList && costRatioNameList.length > 0) {
		$("#BalanceRatio").show();
		var length = costRatioNameList.length;
		var costRatioName = "";
		for (var i = 0; i < length; i++) {
			if (balanceRatioType == '1' && costRatioNameList[i].balanceRatioType == balanceRatioType) {
				costRatioName = "固：" + costRatioNameList[i].balanceRatio;
				break;
			} else if (balanceRatioType == '2' && costRatioNameList[i].balanceRatioType == balanceRatioType) {
				costRatioName = "总：" + costRatioNameList[i].balanceRatio;
				break;
			} else if (balanceRatioType == '3' && costRatioNameList[i].balanceRatioType == balanceRatioType) {
				costRatioName = costRatioName + costRatioNameList[i].chargingStationName + ":" + costRatioNameList[i].balanceRatio + "，";
			}
		}
		$("#CostRatioName").text(costRatioName);
		$("#CostRatioName").attr('title', costRatioName);
		allClick(tabFlag);
	} else {
		showMessge(messageContent["Balance.BalanceRatioDataError"]);
	}
}
function getChargingCostRatioName(data) {
	costRatioNameList = data;
	getBalanceRatioType($("#BalanceRatioType").val());
}
function initTable() {
	$("#summaryBalanceTbody").empty();
	$("#subBranchCompanyBalanceTbody").empty();
	$("#lineBalanceTbody").empty();
	$("#totalChargingCount").html(0);
	$("#totalTradeKWH").html(0);
	$("#totalChargingKWH").html(0);
	$("#totalChargingCost").html("0.00");
	$("#sbcStationCount").html(0);
	$("#sbcLineCount").html(0);
	$("#sbcChargingCount").html(0);
	$("#sbcChargingKWH").html(0);
	$("#sbcChargingCost").html("0.00");
	$("#lineChargingCount").html(0);
	$("#lineCarCount").html(0);
	$("#lineChargingKWH").html(0);
	$("#lineChargingCost").html("0.00");
}
function count(data) {
    var res = [], hash = {};
    for(var i=0, elem; (elem = data[i]) != null; i++)  {
        if (!hash[elem])
        {
            res.push(elem);
            hash[elem] = true;
        }
    }
    return res;
}
function allClick(flag){
	tabFlag = flag;
	var table = undefined;
	if(tabFlag == "summaryBalance"){
		table = document.getElementById('summaryBalanceThead');
		rows = table.rows && table.rows.length;
		if (rows == 0) {
			createTableHead("summaryBalanceThead", summaryBalanceTable);
			scrollTableSuspend("scrollBody", "summaryBalanceTable", "summaryBalanceTable1", "summaryBalanceThead", "scrollHeight");
		}
	} else if (tabFlag == "subBranchCompanyBalance") {
		table = document.getElementById('subBranchCompanyBalanceThead');
		rows = table.rows && table.rows.length;
		if (rows == 0) {
			createTableHead("subBranchCompanyBalanceThead", subBranchCompanyBalanceTable);
			scrollTableSuspend("scrollBody", "subBranchCompanyBalanceTable", "subBranchCompanyBalanceTable1", "subBranchCompanyBalanceThead", "scrollHeight");
		}
		$ajaxList('subBranchCompany', getSubBranchCompanyName);
	} else if (tabFlag == "lineBalance") {
		table = document.getElementById('lineBalanceThead');
		rows = table.rows && table.rows.length;
		if (rows == 0) {
			createTableHead("lineBalanceThead", lineBalanceTable);
			scrollTableSuspend("scrollBody", "lineBalanceTable", "lineBalanceTable1", "lineBalanceThead", "scrollHeight");
		}
		$ajaxList('subBranchCompany', getSubBranchCompany);
	}
	search();
}
function getSubBranchCompanyName(data) {
	$("#subBranchCompanyName").empty();
	$("#subBranchCompanyName").append("<option value=''>请选择</option>");
	var length = data.length;
	for (var i = 0; i < length; i++) {
		$("#subBranchCompanyName").append("<option value='" + data[i].subBranchCompanyID + "'>" + data[i].subBranchCompanyName + "</option>");
	}
}
function getSubBranchCompany(data) {
	$("#SubBranchCompanyID").empty();
	$("#SubBranchCompanyID").append("<option value=''>请选择</option>");
	var length = data.length;
	for (var i = 0; i < length; i++) {
		$("#SubBranchCompanyID").append("<option value='" + data[i].subBranchCompanyID + "'>" + data[i].subBranchCompanyName + "</option>");
	}
}
function changeCarTeam(){
	var subBranchCompanyID = $("#SubBranchCompanyID").val();
	if (subBranchCompanyID) {
		$("#changeTeam").show();
		$("#TeamID").empty();
		$("#TeamID").append("<option value=''>请选择</option>");
		$ajaxList('carTeam', getCarTeam, {"subBranchCompanyID": subBranchCompanyID});
	} else {
		$("#changeTeam").hide();
		$("#TeamID").empty();
		$("#changeLine").hide();
		$("#LineID").empty();
	}
	search();
}
function getCarTeam(data) {
	var length = data.length;
	for (var i = 0; i < length; i++) {
		$("#TeamID").append("<option value='" + data[i].teamID + "'>" + data[i].teamName + "</option>");
	}
}
function changeLine(){
	var teamID = $("#TeamID").val();
	var subBranchCompanyID = $("#SubBranchCompanyID").val();
	if (teamID) {
		$("#changeLine").show();
		$("#LineID").empty();
		$("#LineID").append("<option value=''>请选择</option>");
		$ajaxList('lineName', getLineName,{"teamID": teamID, "subBranchCompanyID": subBranchCompanyID});
	} else {
		$("#changeLine").hide();
		$("#LineID").empty();
	}
	search();
}
function getLineName(data) {
	var length = data.length;
	for (var i = 0; i < length; i++) {
		$("#LineID").append("<option value='" + data[i].lineID + "'>" + data[i].lineName + "</option>");
	}
}
function search(){
	initTable();
	$("#lineIDSubmit").val('');
	$("#subBranchCompanyIDSubmit").val('');
	if (!$("#EffectiveDate").val()) {
		$("#EffectiveDate").tips({
			side : 2,
			msg : "请选择电价有效日期",
			bg : '#AE81FF',
			time : 1
		});
		$("#EffectiveDate").focus();
		return;
	} else if (!$("#BalanceBillID").val()) {
		$("#BalanceBillID").tips({
			side : 2,
			msg : "请选择电力结算单",
			bg : '#AE81FF',
			time : 1
		});
		$("#BalanceBillID").focus();
		return;
	} else {
		if (tabFlag == "summaryBalance") {
			$ajax('searchSummaryBalance', 'costBalanceSearch', searchSummaryBalance);
		} else if (tabFlag == "subBranchCompanyBalance") {
			if (!$("#subBranchCompanyName").val()) {
//				$("#subBranchCompanyName").tips({
//					side : 2,
//					msg : "请选择分公司",
//					bg : '#AE81FF',
//					time : 1
//				});
				$("#subBranchCompanyName").focus();
			} else {
				$("#subBranchCompanyIDSubmit").val($("#subBranchCompanyName").val());
				$ajax('searchSubBranchCompanyBalance', 'costBalanceSearch', searchSubBranchCompanyBalance);
			}
		} else if (tabFlag == "lineBalance") {
			if (!$("#SubBranchCompanyID").val()) {
//				$("#SubBranchCompanyID").tips({
//					side : 2,
//					msg : "请选择分公司",
//					bg : '#AE81FF',
//					time : 1
//				});
				$("#SubBranchCompanyID").focus();
			} else if (!$("#TeamID").val()) {
				$("#TeamID").tips({
					side : 2,
					msg : "请选择车队",
					bg : '#AE81FF',
					time : 1
				});
				$("#TeamID").focus();
				return;
			} else if (!$("#LineID").val()) {
				$("#LineID").tips({
					side : 2,
					msg : "请选择车队",
					bg : '#AE81FF',
					time : 1
				});
				$("#LineID").focus();
				return;
			} else {
				$("#subBranchCompanyIDSubmit").val($("#SubBranchCompanyID").val());
				$("#lineIDSubmit").val($("#LineID").val());
				$ajax('searchLineBalance', 'costBalanceSearch', searchLineBalance);
			}
		}
	}
}
function searchSummaryBalance(data){
	subBranchCompanyNameData = [];
	totalChargingKWHData = [];
	chargingCountData = [];
	totalPriceData = [];
	$("#totalChargingCount").html(data.totalChargingCount || 0);
	$("#totalTradeKWH").html((data.allTotalTradeKWH || 0).toFixed(0));
	$("#totalChargingKWH").html((data.allTotalChargingKWH || 0).toFixed(0));
	$("#totalChargingCost").html((data.totalChargingPrice || 0).toFixed(2));
	summaryBalanceData = data && data.summaryBalanceList || [];
	createTableBody("summaryBalanceTbody", summaryBalanceTable, summaryBalanceData, true, true);
	for(var i=0; i<summaryBalanceData.length; i++){
		subBranchCompanyNameData.push(summaryBalanceData[i].subBranchCompanyName);
		totalChargingKWHData.push(summaryBalanceData[i].totalChargingKWH);
		chargingCountData.push(summaryBalanceData[i].chargingCount);
		totalPriceData.push(summaryBalanceData[i].totalPrice.toFixed(2));
	}
	changeSumEchart();
	setTimeout(hideLoading, 500);
}
function searchSubBranchCompanyBalance(data){
	var stationNameList = [];
	lineNameList = [];
	totalPriceData = [];
	$("#sbcChargingCount").html(data.totalChargingCount || 0);
	$("#sbcChargingKWH").html(data.allTotalChargingKWH || 0);
	$("#sbcChargingCost").html((data.totalChargingPrice || 0).toFixed(2));
	subBranchCompanyBalanceData = data && data.subBranchCompanyBalanceList || [];
	$("#sbcLineCount").html(subBranchCompanyBalanceData.length);
	for(var i=0; i<subBranchCompanyBalanceData.length; i++){
		stationNameList.push(subBranchCompanyBalanceData[i].chargingStationName);
		lineNameList.push(subBranchCompanyBalanceData[i].lineName);
		totalPriceData.push(subBranchCompanyBalanceData[i].totalPrice.toFixed(2));
	}
	$("#sbcStationCount").html(count(stationNameList).length);
	createTableBody("subBranchCompanyBalanceTbody", subBranchCompanyBalanceTable, subBranchCompanyBalanceData, true, true);
	changeEchart();
	setTimeout(hideLoading, 500);
}
function searchLineBalance(data){
	var carCountList = [];
	$("#lineChargingCount").html(data.totalChargingCount || 0);
	$("#lineChargingKWH").html(data.allTotalChargingKWH || 0);
	$("#lineChargingCost").html((data.totalChargingPrice || 0).toFixed(2));
	lineBalanceData = data && data.LineBalanceList || [];
	for(var i=0; i<lineBalanceData.length; i++){
		carCountList.push(lineBalanceData[i].carNumber);
	}
	$("#totalCarCount").html(count(carCountList).length);
	createTableBody("lineBalanceTbody", lineBalanceTable, lineBalanceData, true, true);
//	changeEchart();
	setTimeout(hideLoading, 500);
}
function showMonth(index){
	$('.activeMonthLi').removeClass("activeMonthLi");
	$("#li"+ index).addClass("activeMonthLi");
	var year = $("#showYear").html().replace(/[^0-9]/ig,"");
	index = index >= 10 ? index : "0" + index;
	$("#balanceMonth").val(year + index);
	initChargingPriceName($("#ChargingPriceType").val());
	$ajaxList('balanceBillName', getBalanceBillName, {BalanceMonth: $("#balanceMonth").val()});
}
function changeSumEchart(){
	$("#summaryHistogram").empty();
	if(subBranchCompanyNameData.length == 0){
		$("#summaryHistogram").attr("hidden",true);
		return;
	}
	$("#summaryHistogram").attr("hidden",false);
	myChart = echarts.init(document.getElementById('summaryHistogram'));
    var option = {
            tooltip: {
                trigger: 'axis'
            },
            xAxis: [
                {
                    type: 'category',
                    name: '分公司名称',
                    data: subBranchCompanyNameData
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '充电电量',
                    min: 0,
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: '#09be09',
                        }
                    },
                    axisLabel: {
                        formatter: '{value} '
                    }
                },
                {
                    type: 'value',
                    name: '充电次数',
                    min: 0,
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: '#01b2ac',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '费用',
                    min: 0,
                    position: 'right',
                    offset: 80,
                    axisLine: {
                        lineStyle: {
                            color: '#fe902f',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name:'充电电量',
                    type:'bar',
                    barWidth:10,
                    itemStyle: {
                        normal : {
                            color: '#09be09',
                        }
                    },
                    data:totalChargingKWHData
                },
                {
                	name:'充电次数',
                	type:'bar',
                	barWidth:10,
                	yAxisIndex: 1,
                	itemStyle: {
                        normal : {
                            color: '#01b2ac',
                        }
                    },
                	data: chargingCountData
                },
                {
                	name:'费用',
                	type:'bar',
                	barWidth:10,
                	yAxisIndex: 2,
                	itemStyle: {
                        normal : {
                            color: '#fe902f',
                        }
                    },
                	data: totalPriceData
                }
            ]
        };
    myChart.setOption(option);
}
function changeEchart(){
	$("#subBranchCompanyHistogram").empty();
	if(lineNameList.length == 0){
		$("#subBranchCompanyHistogram").attr("hidden",true);
		return;
	}
	$("#subBranchCompanyHistogram").attr("hidden",false);
	myChart = echarts.init(document.getElementById('subBranchCompanyHistogram'));
    var option = {
            tooltip: {
                trigger: 'axis'
            },
            xAxis: [
                {
                    type: 'category',
                    name: '线路名称',
                    data: lineNameList
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '费用',
                    min: 0,
                    axisLabel: {
                        formatter: '{value} '
                    }
                }
            ],
            series: [
                {
                    name:'费用',
                    type:'bar',
                    barWidth:10,
                    itemStyle: {
                        normal : {
                            color: '#09be09',
                        }
                    },
                    data:totalPriceData
                }
            ]
        };
    myChart.setOption(option);
}
function exportFile(flag){
	exportFlag = flag;
	if (flag == 1) {
		if (summaryBalanceData.length > 0) {
			showMessge("确定导出吗?", "model2");
		} else {
			showMessge("没有数据可导出！");
		}
	} else if (flag == 2) {
		if (subBranchCompanyBalanceData.length > 0) {
			showMessge("确定导出吗?", "model2");
		} else {
			showMessge("没有数据可导出！");
		}
	} else if (flag == 3) {
		if (lineBalanceData.length > 0) {
			showMessge("确定导出吗?", "model2");
		} else {
			showMessge("没有数据可导出！");
		}
	}
}
function sure(){
	showMessge("导出中......");
	$ajax('exportSummaryBalance?checkFlag=&exportFlag=' + exportFlag, undefined, exportFileResult);
}
function exportFileResult(data){
	var result = data && data.result;
	if (result == "Success") {
		showLoading();
		downloadFile('exportSummaryBalance?checkFlag=OK&exportFlag=' + exportFlag);
		showMessge("导出成功，汇总结算文件正在生成！");
		setTimeout(hideLoading, 2000);
	} else if (result == "JsonError") {
		showMessge("导出失败，导出的JSON模板错误 或 不存在！");
	} else if (result == "NotFound") {
		showMessge("导出失败，没有数据可导出！");
	} else {
		showMessge("导出失败，请重新导出 或 联系管理员！");
	}
}